<!-- The exported code uses Tailwind CSS. Install Tailwind CSS in your dev environment to ensure all styles work. -->
<template>
    <div class="min-h-screen bg-gray-50">
        <!-- 顶部导航栏 -->
        <Header />
        <!-- 左侧导航栏 -->
        <aside class="fixed left-0 top-16 bottom-0 w-64 bg-gray-800 text-white z-10 overflow-y-auto">
            <nav class="py-4">
                <div v-for="(menu, index) in mainMenus" :key="index" class="mb-1">
                    <div class="flex items-center px-6 py-3 cursor-pointer hover:bg-gray-700"
                        :class="{ 'bg-blue-700': menu.active }" @click="toggleMenu(index)">
                        <i :class="menu.icon + ' mr-3 w-5 text-center'"></i>
                        <span>{{ menu.name }}</span>
                        <i class="fas fa-chevron-down ml-auto text-xs transition-transform duration-200"
                            :class="{ 'transform rotate-180': menu.expanded }"></i>
                    </div>
                    <div v-if="menu.expanded" class="bg-gray-900">
                        <div v-for="(submenu, subIndex) in menu.subMenus" :key="subIndex"
                            class="flex items-center px-10 py-2 cursor-pointer hover:bg-gray-700"
                            :class="{ 'text-blue-400': submenu.active }" @click="selectSubmenu(index, subIndex)">
                            <a v-if="menu.name === '监测报警模块' && submenu.name === '数据汇聚功能'"
                                href="https://readdy.ai/home/2aadf73d-355f-4962-b7ac-b983b1785a7f/b5a1177e-b0da-4f7d-b25e-4c89773d4c15"
                                data-readdy="true" class="text-sm">{{ submenu.name }}</a>
                            <a v-else-if="submenu.link" :href="submenu.link" data-readdy="true" class="text-sm">{{
                                submenu.name }}</a>
                            <a v-else-if="submenu.link" :href="submenu.link" data-readdy="true" class="text-sm">{{
                                submenu.name }}</a>
                            <span v-else class="text-sm">{{ submenu.name }}</span>
                        </div>
                    </div>
                </div>
            </nav>
        </aside>
        <!-- 主内容区域 -->
        <main class="pt-16 pl-64">
            <div class="container mx-auto p-6">
                <!-- 面包屑导航 -->
                <div class="flex items-center text-sm mb-6 text-gray-500">
                    <span>首页</span>
                    <i class="fas fa-chevron-right mx-2 text-xs"></i>
                    <span>监测报警</span>
                    <i class="fas fa-chevron-right mx-2 text-xs"></i>
                    <span class="text-blue-600">监测指标统计</span>
                </div>
                <!-- 指标概览卡片 -->
                <div class="grid grid-cols-4 gap-6 mb-6">
                    <div v-for="(card, index) in overviewCards" :key="index"
                        class="bg-white rounded-lg shadow-sm p-6 flex items-center">
                        <div class="w-12 h-12 rounded-lg flex items-center justify-center" :class="card.bgColor">
                            <i :class="card.icon + ' text-white text-xl'"></i>
                        </div>
                        <div class="ml-4">
                            <h3 class="text-gray-500 text-sm">{{ card.title }}</h3>
                            <div class="flex items-end mt-1">
                                <span class="text-2xl font-bold">{{ card.value }}</span>
                                <span class="text-xs ml-2"
                                    :class="card.trend === 'up' ? 'text-red-500' : 'text-green-500'">
                                    <i :class="card.trend === 'up' ? 'fas fa-arrow-up' : 'fas fa-arrow-down'"></i>
                                    {{ card.percentage }}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 指标趋势分析 -->
                <div class="grid grid-cols-3 gap-6 mb-6">
                    <!-- 指标趋势图 -->
                    <div class="bg-white rounded-lg shadow-sm col-span-2 overflow-hidden">
                        <div class="p-4 border-b border-gray-100 flex justify-between items-center">
                            <h2 class="font-bold text-gray-700">指标趋势分析</h2>
                            <div class="flex space-x-2">
                                <button v-for="(period, idx) in timePeriods" :key="idx"
                                    class="px-3 py-1 text-sm rounded !rounded-button whitespace-nowrap cursor-pointer"
                                    :class="selectedPeriod === period.value ? 'bg-blue-600 text-white hover:bg-blue-700' : 'bg-gray-100 hover:bg-gray-200'"
                                    @click="changeTimePeriod(period.value)">
                                    {{ period.label }}
                                </button>
                            </div>
                        </div>
                        <div class="p-4">
                            <div id="indicatorTrendChart" class="h-80" ref="indicatorTrendChart"></div>
                        </div>
                    </div>
                    <!-- 异常指标TOP5 -->
                    <div class="bg-white rounded-lg shadow-sm">
                        <div class="p-4 border-b border-gray-100 flex justify-between items-center">
                            <h2 class="font-bold text-gray-700">异常指标 TOP5</h2>
                            <button @click="openAllIndicators"
                                class="text-blue-600 text-sm !rounded-button whitespace-nowrap cursor-pointer">查看全部</button>
                        </div>
                        <div class="p-4 overflow-y-auto h-80">
                            <div v-for="(indicator, index) in abnormalIndicators" :key="index"
                                class="border-l-4 p-3 mb-3 bg-gray-50" :class="{
                                    'border-red-500': indicator.level === 'critical',
                                    'border-orange-500': indicator.level === 'high',
                                    'border-yellow-500': indicator.level === 'medium',
                                    'border-blue-500': indicator.level === 'low'
                                }">
                                <div class="flex justify-between items-start">
                                    <span class="inline-block px-2 py-1 text-xs rounded-full text-white mb-2" :class="{
                                        'bg-red-500': indicator.level === 'critical',
                                        'bg-orange-500': indicator.level === 'high',
                                        'bg-yellow-500': indicator.level === 'medium',
                                        'bg-blue-500': indicator.level === 'low'
                                    }">
                                        {{ indicator.levelText }}
                                    </span>
                                    <span class="text-xs text-gray-500">{{ indicator.time }}</span>
                                </div>
                                <h4 class="font-medium text-gray-800">{{ indicator.name }}</h4>
                                <p class="text-sm text-gray-600 mt-1">当前值: <span class="font-semibold"
                                        :class="{ 'text-red-600': indicator.level === 'critical' || indicator.level === 'high' }">{{
                                            indicator.value }}</span> {{ indicator.unit }}</p>
                                <div class="flex justify-between items-center mt-2">
                                    <span class="text-xs text-gray-500">{{ indicator.location }}</span>
                                    <button @click="openIndicatorDetail(indicator)"
                                        class="text-xs text-blue-600 !rounded-button whitespace-nowrap cursor-pointer">详情</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 指标分析图表 -->
                <div class="grid grid-cols-3 gap-6 mb-6">
                    <!-- 指标类型分布 -->
                    <div class="bg-white rounded-lg shadow-sm">
                        <div class="p-4 border-b border-gray-100">
                            <h2 class="font-bold text-gray-700">指标类型分布</h2>
                        </div>
                        <div class="p-4">
                            <div id="indicatorTypeChart" class="h-64" ref="indicatorTypeChart"></div>
                        </div>
                    </div>
                    <!-- 指标达标率趋势 -->
                    <div class="bg-white rounded-lg shadow-sm">
                        <div class="p-4 border-b border-gray-100">
                            <h2 class="font-bold text-gray-700">指标达标率趋势</h2>
                        </div>
                        <div class="p-4">
                            <div id="complianceRateChart" class="h-64" ref="complianceRateChart"></div>
                        </div>
                    </div>
                    <!-- 异常指标来源分布 -->
                    <div class="bg-white rounded-lg shadow-sm">
                        <div class="p-4 border-b border-gray-100">
                            <h2 class="font-bold text-gray-700">异常指标来源分布</h2>
                        </div>
                        <div class="p-4">
                            <div id="abnormalSourceChart" class="h-64" ref="abnormalSourceChart"></div>
                        </div>
                    </div>
                </div>
                <!-- 区域指标对比分析 -->
                <div class="grid grid-cols-2 gap-6">
                    <!-- 区域指标雷达图 -->
                    <div class="bg-white rounded-lg shadow-sm">
                        <div class="p-4 border-b border-gray-100 flex justify-between items-center">
                            <h2 class="font-bold text-gray-700">区域指标对比</h2>
                            <div class="flex space-x-2">
                                <select v-model="selectedArea" @change="initAreaComparisonChart"
                                    class="px-3 py-1 text-sm bg-gray-100 border-none rounded !rounded-button whitespace-nowrap cursor-pointer focus:outline-none focus:ring-2 focus:ring-blue-500">
                                    <option v-for="area in areas" :key="area" :value="area">{{ area }}</option>
                                </select>
                            </div>
                        </div>
                        <div class="p-4">
                            <div id="areaComparisonChart" class="h-80" ref="areaComparisonChart"></div>
                        </div>
                    </div>
                    <!-- 区域指标排名 -->
                    <div class="bg-white rounded-lg shadow-sm">
                        <div class="p-4 border-b border-gray-100 flex justify-between items-center">
                            <h2 class="font-bold text-gray-700">区域指标排名</h2>
                            <div class="flex space-x-2">
                                <select v-model="selectedIndicatorType" @change="updateRankingData"
                                    class="px-3 py-1 text-sm bg-gray-100 border-none rounded !rounded-button whitespace-nowrap cursor-pointer focus:outline-none focus:ring-2 focus:ring-blue-500">
                                    <option v-for="type in indicatorTypes" :key="type.value" :value="type.value">{{
                                        type.label }}</option>
                                </select>
                            </div>
                        </div>
                        <div class="p-4">
                            <div class="overflow-y-auto h-80">
                                <table class="min-w-full divide-y divide-gray-200">
                                    <thead class="bg-gray-50">
                                        <tr>
                                            <th scope="col"
                                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                排名</th>
                                            <th scope="col"
                                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                区域</th>
                                            <th scope="col"
                                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                指标值</th>
                                            <th scope="col"
                                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                达标率</th>
                                            <th scope="col"
                                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                趋势</th>
                                        </tr>
                                    </thead>
                                    <tbody class="bg-white divide-y divide-gray-200">
                                        <tr v-for="(item, index) in currentRankingData" :key="index">
                                            <td class="px-6 py-4 whitespace-nowrap">
                                                <div class="flex items-center">
                                                    <span
                                                        class="flex items-center justify-center w-6 h-6 rounded-full text-xs font-medium"
                                                        :class="{
                                                            'bg-yellow-100 text-yellow-800': index === 0,
                                                            'bg-gray-100 text-gray-800': index === 1,
                                                            'bg-orange-100 text-orange-800': index === 2,
                                                            'bg-white text-gray-500': index > 2
                                                        }">
                                                        {{ index + 1 }}
                                                    </span>
                                                </div>
                                            </td>
                                            <td class="px-6 py-4 whitespace-nowrap">
                                                <div class="text-sm font-medium text-gray-900">{{ item.area }}</div>
                                            </td>
                                            <td class="px-6 py-4 whitespace-nowrap">
                                                <div class="text-sm text-gray-900">{{ item.value }}</div>
                                            </td>
                                            <td class="px-6 py-4 whitespace-nowrap">
                                                <div class="w-full bg-gray-200 rounded-full h-2.5">
                                                    <div class="h-2.5 rounded-full"
                                                        :style="{ width: item.complianceRate + '%', backgroundColor: getComplianceColor(item.complianceRate) }">
                                                    </div>
                                                </div>
                                                <div class="text-xs text-gray-500 mt-1">{{ item.complianceRate }}%</div>
                                            </td>
                                            <td class="px-6 py-4 whitespace-nowrap">
                                                <span :class="item.trend === 'up' ? 'text-green-600' : 'text-red-600'">
                                                    <i
                                                        :class="item.trend === 'up' ? 'fas fa-arrow-up' : 'fas fa-arrow-down'"></i>
                                                    {{ item.trendValue }}%
                                                </span>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
    <!-- 异常指标详情弹框 -->
    <div v-if="showIndicatorDetail"
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[60]">
        <div class="bg-white rounded-lg shadow-xl w-2/3 max-w-4xl mx-4 max-h-[90vh] overflow-hidden ">
            <!-- 标题栏 -->
            <div class="p-6 border-b border-gray-100 flex justify-between items-center">
                <h2 class="text-xl font-bold text-gray-800">异常指标详情</h2>
                <button @click="closeIndicatorDetail"
                    class="text-gray-400 hover:text-gray-600 transition-colors duration-200">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>

            <!-- 内容区域 -->
            <div class="p-6 overflow-y-auto max-h-[calc(90vh-120px)]">
                <!-- 基本信息 -->
                <div class="grid grid-cols-2 gap-6 mb-6">
                    <div class="bg-gray-50 rounded-lg p-4">
                        <h3 class="text-sm font-medium text-gray-500 mb-2">基本信息</h3>
                        <div class="space-y-2">
                            <div class="flex justify-between">
                                <span class="text-sm text-gray-600">指标名称：</span>
                                <span class="text-sm font-medium">{{ selectedIndicator.name }}</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-sm text-gray-600">异常级别：</span>
                                <span class="text-sm font-medium" :class="{
                                    'text-red-600': selectedIndicator.level === 'critical',
                                    'text-orange-600': selectedIndicator.level === 'high',
                                    'text-yellow-600': selectedIndicator.level === 'medium',
                                    'text-blue-600': selectedIndicator.level === 'low'
                                }">{{ selectedIndicator.levelText }}</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-sm text-gray-600">当前位置：</span>
                                <span class="text-sm font-medium">{{ selectedIndicator.location }}</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-sm text-gray-600">发生时间：</span>
                                <span class="text-sm font-medium">{{ selectedIndicator.time }}</span>
                            </div>
                        </div>
                    </div>

                    <div class="bg-gray-50 rounded-lg p-4">
                        <h3 class="text-sm font-medium text-gray-500 mb-2">数值信息</h3>
                        <div class="space-y-2">
                            <div class="flex justify-between">
                                <span class="text-sm text-gray-600">当前值：</span>
                                <span class="text-sm font-medium" :class="{
                                    'text-red-600': selectedIndicator.level === 'critical' || selectedIndicator.level === 'high'
                                }">{{ selectedIndicator.value }}</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-sm text-gray-600">标准范围：</span>
                                <span class="text-sm font-medium">20-30 kPa</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-sm text-gray-600">偏差值：</span>
                                <span class="text-sm font-medium text-red-600">+8.5 kPa</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-sm text-gray-600">单位：</span>
                                <span class="text-sm font-medium">{{ selectedIndicator.unit }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 底部操作栏 -->
            <div class="p-6 border-t border-gray-100 flex justify-end">
                <button @click="closeIndicatorDetail"
                    class="px-4 py-2 text-sm text-gray-600 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors duration-200">
                    关闭
                </button>
            </div>
        </div>
    </div>
    <!-- 所有异常指标弹框 -->
    <div v-if="showAllIndicators" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div class="bg-white rounded-lg shadow-xl w-4/5 max-w-6xl mx-4 max-h-[90vh] overflow-hidden">
            <!-- 标题栏 -->
            <div class="p-6 border-b border-gray-100 flex justify-between items-center">
                <h2 class="text-xl font-bold text-gray-800">所有异常指标</h2>
                <button @click="closeAllIndicators"
                    class="text-gray-400 hover:text-gray-600 transition-colors duration-200">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>

            <!-- 内容区域 -->
            <div class="p-6 overflow-y-auto max-h-[calc(90vh-120px)]">
                <div class="grid grid-cols-2 gap-4">
                    <div v-for="(indicator, index) in abnormalIndicators" :key="index"
                        class="border-l-4 p-4 bg-gray-50 hover:bg-gray-100 cursor-pointer" :class="{
                            'border-red-500': indicator.level === 'critical',
                            'border-orange-500': indicator.level === 'high',
                            'border-yellow-500': indicator.level === 'medium',
                            'border-blue-500': indicator.level === 'low'
                        }">
                        <div class="flex justify-between items-start">
                            <span class="inline-block px-2 py-1 text-xs rounded-full text-white mb-2" :class="{
                                'bg-red-500': indicator.level === 'critical',
                                'bg-orange-500': indicator.level === 'high',
                                'bg-yellow-500': indicator.level === 'medium',
                                'bg-blue-500': indicator.level === 'low'
                            }">
                                {{ indicator.levelText }}
                            </span>
                            <span class="text-xs text-gray-500">{{ indicator.time }}</span>
                        </div>
                        <h4 class="font-medium text-gray-800">{{ indicator.name }}</h4>
                        <p class="text-sm text-gray-600 mt-1">当前值: <span class="font-semibold"
                                :class="{ 'text-red-600': indicator.level === 'critical' || indicator.level === 'high' }">{{
                                    indicator.value }}</span> {{ indicator.unit }}</p>
                        <div class="flex justify-between items-center mt-2">
                            <span class="text-xs text-gray-500">{{ indicator.location }}</span>
                            <button @click="openIndicatorDetail(indicator)"
                                class="text-xs text-blue-600 hover:text-blue-800 !rounded-button whitespace-nowrap cursor-pointer">详情</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 底部操作栏 -->
            <div class="p-6 border-t border-gray-100 flex justify-end">
                <button @click="closeAllIndicators"
                    class="px-4 py-2 text-sm text-gray-600 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors duration-200">
                    关闭
                </button>
            </div>
        </div>
    </div>

</template>
<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts';
import { useRouter } from 'vue-router'
import Header from '../components/Header.vue';

const showIndicatorDetail = ref(false)
const selectedIndicator = ref(null)
const openIndicatorDetail = (indicator) => {
    selectedIndicator.value = indicator
    showIndicatorDetail.value = true
    //     nextTick(() => {
    //         initIndicatorDetailChart()
    //     })
}

const closeIndicatorDetail = () => {
    showIndicatorDetail.value = false
    selectedIndicator.value = null
}
// 添加弹框控制
const showAllIndicators = ref(false)
const openAllIndicators = () => {
    showAllIndicators.value = true
}

const closeAllIndicators = () => {
    showAllIndicators.value = false
}

const mainMenus = ref([
    {
        name: '监测报警',
        icon: 'fas fa-bell',
        expanded: true,
        active: true,
        subMenus: [
            { name: '数据汇聚功能', active: false, link: '/data-aggregation' },
            { name: '监测指标统计', active: true, link: '/monitoring-indicators' },
            { name: '区域化展示', active: false, link: '/regional-display' }
        ]
    },
    {
        name: '风险研判',
        icon: 'fas fa-exclamation-triangle',
        expanded: false,
        active: false,
        subMenus: [
            { name: '智能风险评估', active: false, link: '/intelligent-risk-assessment' },
            { name: '预警信息推送', active: false, link: '/risk-warning-push' },
            { name: '风险管理与分析', active: false, link: '/risk-analysis' },
            // { name: '重点风险提示', active: false, link: '/focus' },
        ]
    },
    {
        name: '在线巡查',
        icon: 'fas fa-search',
        expanded: false,
        active: false,
        subMenus: [
            { name: '企业信息汇总', active: false, link: '/summary-information' },
            { name: '巡查功能', active: false, link: '/patrol' },
            { name: '检索功能', active: false, link: 'search' },
            { name: '一屏汇聚展示', active: false, link: '/screen-display' }
        ]
    },
    {
        name: '综合分析',
        icon: 'fas fa-chart-line',
        expanded: false,
        active: false,
        subMenus: [
            { name: '联网与设备分析', active: false, link: '/equipment' },
            { name: '应用情况分析', active: false, link: '/application' },
            { name: '数据质量分析', active: false, link: '/data-quality' },
            { name: '定期专题报告', active: false, link: 'report' }
        ]
    },
    {
        name: '系统管理',
        icon: 'fas fa-cog',
        expanded: false,
        active: false,
        subMenus: [
            { name: '用户权限管理', active: false, link: 'user-permission' },
            { name: '系统配置管理', active: false, link: 'system-manage' },
            { name: '数据管理', active: false, link: 'data-manage' },
            { name: '系统监控与维护', active: false, link: 'monitoring' }
        ]
    }
])

// 路由实例用于整块区域点击跳转
const router = useRouter()
const overviewCards = ref([
    {
        title: '监测指标总数',
        value: '248',
        percentage: '3.2%',
        trend: 'up',
        icon: 'fas fa-chart-line',
        bgColor: 'bg-blue-600'
    },
    {
        title: '异常指标数量',
        value: '36',
        percentage: '8.5%',
        trend: 'up',
        icon: 'fas fa-exclamation-triangle',
        bgColor: 'bg-red-500'
    },
    {
        title: '预警指标数量',
        value: '52',
        percentage: '4.7%',
        trend: 'down',
        icon: 'fas fa-bell',
        bgColor: 'bg-orange-500'
    },
    {
        title: '待处理预警数',
        value: '23',
        percentage: '2.1%',
        trend: 'down',
        icon: 'fas fa-tasks',
        bgColor: 'bg-green-500'
    }
])
const abnormalIndicators = ref([
    {
        level: 'critical',
        levelText: '严重异常',
        time: '10:35:12',
        name: '高炉煤气压力',
        value: '28.5 kPa',
        unit: 'kPa',
        location: '炼铁厂 - 3号高炉'
    },
    {
        level: 'high',
        levelText: '高度异常',
        time: '09:47:23',
        name: '转炉温度',
        value: '1650 ℃',
        unit: '℃',
        location: '炼钢厂 - 2号转炉'
    },
    {
        level: 'high',
        levelText: '高度异常',
        time: '09:22:56',
        name: '废气排放浓度',
        value: '42 mg/m³',
        unit: 'mg/m³',
        location: '烧结厂 - 1号烧结机'
    },
    {
        level: 'medium',
        levelText: '中度异常',
        time: '08:53:41',
        name: '冷却水流量',
        value: '185 m³/h',
        unit: 'm³/h',
        location: '连铸车间 - 冷却系统'
    },
    {
        level: 'low',
        levelText: '轻度异常',
        time: '08:15:07',
        name: '电机振动值',
        value: '4.8 mm/s',
        unit: 'mm/s',
        location: '轧钢厂 - 主传动电机'
    }
])
const timePeriods = ref([
    { label: '日', value: 'day' },
    { label: '周', value: 'week' },
    { label: '月', value: 'month' }
])
const selectedPeriod = ref('day')
const areas = ref(['炼铁厂', '炼钢厂', '轧钢厂', '烧结厂', '动力厂', '全部区域'])
const selectedArea = ref('全部区域')
const indicatorTypes = ref([
    { label: '温度指标', value: 'temperature' },
    { label: '压力指标', value: 'pressure' },
    { label: '流量指标', value: 'flow' },
    { label: '浓度指标', value: 'concentration' },
    { label: '振动指标', value: 'vibration' }
])
const selectedIndicatorType = ref('temperature')
// 图表引用
const indicatorTrendChart = ref(null)
const indicatorTypeChart = ref(null)
const complianceRateChart = ref(null)
const abnormalSourceChart = ref(null)
const areaComparisonChart = ref(null)

const toggleMenu = (index) => {
    mainMenus.value[index].expanded = !mainMenus.value[index].expanded
    if (mainMenus.value[index].expanded) {
        mainMenus.value.forEach((menu, i) => {
            if (i !== index) {
                menu.expanded = false
            }
        })
    }
}
const selectSubmenu = (menuIndex, submenuIndex) => {
    // 重置所有菜单的激活状态
    mainMenus.value.forEach(menu => {
        menu.active = false
        menu.subMenus.forEach(submenu => {
            submenu.active = false
        })
    })
    mainMenus.value[menuIndex].active = true
    mainMenus.value[menuIndex].subMenus[submenuIndex].active = true
    const link = mainMenus.value[menuIndex].subMenus[submenuIndex].link
    if (link) {
        const dest = link.startsWith('/') ? link : `/${link}`
        router.push(dest)
    }
}
const changeTimePeriod = (period) => {
    selectedPeriod.value = period
    initIndicatorTrendChart()
}

const getComplianceColor = (rate) => {
    if (rate >= 90) return '#48bb78'
    if (rate >= 80) return '#4299e1'
    if (rate >= 70) return '#ecc94b'
    if (rate >= 60) return '#ed8936'
    return '#f56565'
}
// 处理窗口大小变化
const handleResize = () => {
    const charts = [
        indicatorTrendChart.value,
        indicatorTypeChart.value,
        complianceRateChart.value,
        abnormalSourceChart.value,
        areaComparisonChart.value
    ]
    charts.forEach(ref => {
        if (ref) {
            const chart = echarts.getInstanceByDom(ref)
            if (chart) {
                chart.resize()
            }
        }
    })
}
const initIndicatorTrendChart = () => {
    if (!indicatorTrendChart.value) return
    const chart = echarts.init(indicatorTrendChart.value)
    // 根据选择的时间周期生成不同的数据
    let xAxisData = [];
    let normalData = [];
    let abnormalData = [];
    let warningData = [];
    if (selectedPeriod.value === 'day') {
        xAxisData = ['00:00', '02:00', '04:00', '06:00', '08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00'];
        normalData = [210, 205, 208, 215, 220, 225, 228, 230, 225, 220, 215, 212];
        abnormalData = [20, 18, 22, 25, 30, 35, 32, 28, 26, 24, 22, 20];
        warningData = [35, 32, 38, 42, 45, 50, 48, 45, 42, 40, 38, 36];
    } else if (selectedPeriod.value === 'week') {
        xAxisData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        normalData = [215, 220, 225, 230, 228, 222, 218];
        abnormalData = [25, 28, 32, 35, 30, 26, 24];
        warningData = [40, 45, 48, 52, 50, 45, 42];
    } else if (selectedPeriod.value === 'month') {
        xAxisData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
        normalData = [200, 205, 210, 215, 220, 225, 230, 228, 225, 220, 215, 210];
        abnormalData = [22, 24, 26, 28, 32, 35, 38, 36, 34, 30, 28, 25];
        warningData = [38, 40, 42, 45, 48, 52, 55, 53, 50, 48, 45, 42];
    }
    const option = {
        animation: false,
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: ['正常指标', '异常指标', '预警指标'],
            right: 10,
            top: 0
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: xAxisData
        },
        yAxis: {
            type: 'value',
            name: '指标数量'
        },
        series: [
            {
                name: '正常指标',
                type: 'line',
                stack: 'Total',
                smooth: true,
                lineStyle: {
                    width: 3,
                    color: '#4299e1'
                },
                areaStyle: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                            {
                                offset: 0,
                                color: 'rgba(66, 153, 225, 0.5)'
                            },
                            {
                                offset: 1,
                                color: 'rgba(66, 153, 225, 0.05)'
                            }
                        ]
                    }
                },
                data: normalData
            },
            {
                name: '异常指标',
                type: 'line',
                stack: 'Total',
                smooth: true,
                lineStyle: {
                    width: 3,
                    color: '#f56565'
                },
                areaStyle: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                            {
                                offset: 0,
                                color: 'rgba(245, 101, 101, 0.5)'
                            },
                            {
                                offset: 1,
                                color: 'rgba(245, 101, 101, 0.05)'
                            }
                        ]
                    }
                },
                data: abnormalData
            },
            {
                name: '预警指标',
                type: 'line',
                stack: 'Total',
                smooth: true,
                lineStyle: {
                    width: 3,
                    color: '#ed8936'
                },
                areaStyle: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                            {
                                offset: 0,
                                color: 'rgba(237, 137, 54, 0.5)'
                            },
                            {
                                offset: 1,
                                color: 'rgba(237, 137, 54, 0.05)'
                            }
                        ]
                    }
                },
                data: warningData
            }
        ]
    };
    chart.setOption(option);
}
const initIndicatorTypeChart = () => {
    if (!indicatorTypeChart.value) return
    const chart = echarts.init(indicatorTypeChart.value)
    const option = {
        animation: false,
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            right: 10,
            top: 'center',
            data: ['温度指标', '压力指标', '流量指标', '浓度指标', '振动指标']
        },
        series: [
            {
                name: '指标类型',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '14',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: [
                    { value: 65, name: '温度指标', itemStyle: { color: '#f56565' } },
                    { value: 52, name: '压力指标', itemStyle: { color: '#4299e1' } },
                    { value: 48, name: '流量指标', itemStyle: { color: '#48bb78' } },
                    { value: 45, name: '浓度指标', itemStyle: { color: '#ecc94b' } },
                    { value: 38, name: '振动指标', itemStyle: { color: '#ed8936' } }
                ]
            }
        ]
    };
    chart.setOption(option);
}
const initComplianceRateChart = () => {
    if (!complianceRateChart.value) return
    const chart = echarts.init(complianceRateChart.value)
    const option = {
        animation: false,
        tooltip: {
            trigger: 'axis'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月']
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: '{value}%'
            },
            min: 70,
            max: 100
        },
        series: [
            {
                name: '达标率',
                type: 'line',
                data: [82, 85, 88, 86, 90, 92, 95],
                smooth: true,
                lineStyle: {
                    width: 3,
                    color: '#48bb78'
                },
                markLine: {
                    silent: true,
                    lineStyle: {
                        color: '#ed8936'
                    },
                    data: [
                        {
                            yAxis: 85,
                            name: '警戒线'
                        }
                    ]
                }
            }
        ]
    };
    chart.setOption(option);
}
const initAbnormalSourceChart = () => {
    if (!abnormalSourceChart.value) return
    const chart = echarts.init(abnormalSourceChart.value)
    const option = {
        animation: false,
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'value',
            name: '异常数量'
        },
        yAxis: {
            type: 'category',
            data: ['炼铁厂', '炼钢厂', '轧钢厂', '烧结厂', '动力厂']
        },
        series: [
            {
                name: '异常数量',
                type: 'bar',
                data: [
                    {
                        value: 12,
                        itemStyle: {
                            color: '#f56565'
                        }
                    },
                    {
                        value: 9,
                        itemStyle: {
                            color: '#f56565'
                        }
                    },
                    {
                        value: 7,
                        itemStyle: {
                            color: '#f56565'
                        }
                    },
                    {
                        value: 5,
                        itemStyle: {
                            color: '#f56565'
                        }
                    },
                    {
                        value: 3,
                        itemStyle: {
                            color: '#f56565'
                        }
                    }
                ]
            }
        ]
    };
    chart.setOption(option);
}
const initAreaComparisonChart = () => {
    if (!areaComparisonChart.value) return
    // 获取已存在的图表实例
    const existingChart = echarts.getInstanceByDom(areaComparisonChart.value)

    // 如果存在已实例化的图表，先销毁
    if (existingChart) {
        existingChart.dispose()
    }

    // 初始化新图表
    const chart = echarts.init(areaComparisonChart.value)

    // 根据选择的区域过滤数据
    const getAreaData = (areaName) => {
        const areaDataMap = {
            '炼铁厂': [95, 90, 85, 88, 92],
            '炼钢厂': [88, 94, 90, 85, 86],
            '轧钢厂': [86, 85, 92, 88, 90],
            '烧结厂': [82, 80, 85, 90, 84],
            '动力厂': [90, 88, 85, 82, 95]
        }
        return areaDataMap[areaName] || []
    }

    const currentAreaData = selectedArea.value === '全部区域'
        ? [
            {
                value: [95, 90, 85, 88, 92],
                name: '炼铁厂',
                symbol: 'circle',
                symbolSize: 8,
                lineStyle: { width: 2 },
                areaStyle: { opacity: 0.3 }
            },
            {
                value: [88, 94, 90, 85, 86],
                name: '炼钢厂',
                symbol: 'circle',
                symbolSize: 8,
                lineStyle: { width: 2 },
                areaStyle: { opacity: 0.3 }
            },
            {
                value: [86, 85, 92, 88, 90],
                name: '轧钢厂',
                symbol: 'circle',
                symbolSize: 8,
                lineStyle: { width: 2 },
                areaStyle: { opacity: 0.3 }
            },
            {
                value: [82, 80, 85, 90, 84],
                name: '烧结厂',
                symbol: 'circle',
                symbolSize: 8,
                lineStyle: { width: 2 },
                areaStyle: { opacity: 0.3 }
            },
            {
                value: [90, 88, 85, 82, 95],
                name: '动力厂',
                symbol: 'circle',
                symbolSize: 8,
                lineStyle: { width: 2 },
                areaStyle: { opacity: 0.3 }
            }
        ]
        : [
            {
                value: getAreaData(selectedArea.value),
                name: selectedArea.value,
                symbol: 'circle',
                symbolSize: 8,
                lineStyle: { width: 2 },
                areaStyle: { opacity: 0.3 }
            }
        ]
    const option = {
        animation: false,
        tooltip: {
            trigger: 'item'
        },
        legend: {
            data: selectedArea.value === '全部区域'
                ? ['炼铁厂', '炼钢厂', '轧钢厂', '烧结厂', '动力厂']
                : [selectedArea.value],
            right: 10,
            top: 0
        },
        radar: {
            indicator: [
                { name: '温度指标', max: 100 },
                { name: '压力指标', max: 100 },
                { name: '流量指标', max: 100 },
                { name: '浓度指标', max: 100 },
                { name: '振动指标', max: 100 }
            ],
            radius: '65%',
            center: ['50%', '55%']
        },
        series: [
            {
                type: 'radar',
                name: '区域指标对比',
                data: currentAreaData
            }
        ]
    }
    chart.setOption(option);
}
const areaRankingData = ref({
    temperature: [  // 温度指标
        { area: '炼钢厂', value: '95.7', complianceRate: 92, trend: 'up', trendValue: 2.5 },
        { area: '动力厂', value: '93.2', complianceRate: 88, trend: 'up', trendValue: 1.8 },
        { area: '炼铁厂', value: '89.5', complianceRate: 85, trend: 'up', trendValue: 0.9 },
        { area: '轧钢厂', value: '87.3', complianceRate: 82, trend: 'down', trendValue: 1.2 },
        { area: '烧结厂', value: '85.1', complianceRate: 78, trend: 'down', trendValue: 2.3 },
        { area: '原料厂', value: '82.6', complianceRate: 75, trend: 'up', trendValue: 1.5 },
        { area: '运输部', value: '80.9', complianceRate: 73, trend: 'down', trendValue: 0.8 },
        { area: '质检部', value: '79.4', complianceRate: 70, trend: 'up', trendValue: 1.1 }
    ],
    pressure: [  // 压力指标
        { area: '炼铁厂', value: '92.8', complianceRate: 90, trend: 'up', trendValue: 2.1 },
        { area: '炼钢厂', value: '90.5', complianceRate: 87, trend: 'up', trendValue: 1.5 },
        { area: '动力厂', value: '88.3', complianceRate: 85, trend: 'down', trendValue: 0.9 },
        { area: '轧钢厂', value: '86.7', complianceRate: 83, trend: 'up', trendValue: 1.3 },
        { area: '烧结厂', value: '84.2', complianceRate: 80, trend: 'down', trendValue: 1.8 },
        { area: '原料厂', value: '81.9', complianceRate: 77, trend: 'up', trendValue: 1.2 },
        { area: '运输部', value: '79.6', complianceRate: 74, trend: 'down', trendValue: 0.7 },
        { area: '质检部', value: '77.3', complianceRate: 71, trend: 'up', trendValue: 1.0 }
    ],
    flow: [  // 流量指标
        { area: '动力厂', value: '94.2', complianceRate: 91, trend: 'up', trendValue: 2.3 },
        { area: '炼铁厂', value: '91.8', complianceRate: 88, trend: 'up', trendValue: 1.7 },
        { area: '炼钢厂', value: '89.5', complianceRate: 86, trend: 'down', trendValue: 1.1 },
        { area: '轧钢厂', value: '87.1', complianceRate: 84, trend: 'up', trendValue: 1.4 },
        { area: '烧结厂', value: '84.8', complianceRate: 81, trend: 'down', trendValue: 1.9 },
        { area: '原料厂', value: '82.4', complianceRate: 78, trend: 'up', trendValue: 1.3 },
        { area: '运输部', value: '80.1', complianceRate: 75, trend: 'down', trendValue: 0.8 },
        { area: '质检部', value: '77.8', complianceRate: 72, trend: 'up', trendValue: 1.1 }
    ],
    concentration: [  // 浓度指标
        { area: '烧结厂', value: '93.5', complianceRate: 89, trend: 'up', trendValue: 2.2 },
        { area: '炼铁厂', value: '91.2', complianceRate: 87, trend: 'up', trendValue: 1.6 },
        { area: '炼钢厂', value: '88.9', complianceRate: 85, trend: 'down', trendValue: 1.0 },
        { area: '动力厂', value: '86.6', complianceRate: 83, trend: 'up', trendValue: 1.5 },
        { area: '轧钢厂', value: '84.3', complianceRate: 80, trend: 'down', trendValue: 1.7 },
        { area: '原料厂', value: '82.0', complianceRate: 77, trend: 'up', trendValue: 1.2 },
        { area: '运输部', value: '79.7', complianceRate: 74, trend: 'down', trendValue: 0.9 },
        { area: '质检部', value: '77.4', complianceRate: 71, trend: 'up', trendValue: 1.1 }
    ],
    vibration: [  // 振动指标
        { area: '轧钢厂', value: '95.1', complianceRate: 92, trend: 'up', trendValue: 2.4 },
        { area: '动力厂', value: '92.7', complianceRate: 89, trend: 'up', trendValue: 1.8 },
        { area: '炼铁厂', value: '90.3', complianceRate: 86, trend: 'down', trendValue: 1.2 },
        { area: '炼钢厂', value: '87.9', complianceRate: 83, trend: 'up', trendValue: 1.5 },
        { area: '烧结厂', value: '85.6', complianceRate: 80, trend: 'down', trendValue: 1.6 },
        { area: '原料厂', value: '83.2', complianceRate: 77, trend: 'up', trendValue: 1.1 },
        { area: '运输部', value: '80.9', complianceRate: 74, trend: 'down', trendValue: 0.8 },
        { area: '质检部', value: '78.6', complianceRate: 71, trend: 'up', trendValue: 1.0 }
    ]
})
// 添加当前显示的排名数据
const currentRankingData = ref(areaRankingData.value.temperature)
const updateRankingData = () => {
    // 根据选择的指标类型获取对应数据
    const currentData = areaRankingData.value[selectedIndicatorType.value]
    // 更新显示的数据
    currentRankingData.value = [...currentData]
}
// 生命周期钩子
onMounted(() => {
    initIndicatorTrendChart()
    initIndicatorTypeChart()
    initComplianceRateChart()
    initAbnormalSourceChart()
    initAreaComparisonChart()
    window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
    window.removeEventListener('resize', handleResize)

})
</script>
<style scoped>
/* 自定义样式 */
.monitoring__chart-container {
    position: relative;
    width: 100%;
    height: 100%;
}

/* 隐藏input number的箭头 */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

input[type="number"] {
    -moz-appearance: textfield;
}

/* 自定义选择器样式 */
select {
    appearance: none;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%236B7280' d='M6 8.825L1.175 4 2.05 3.125 6 7.075 9.95 3.125 10.825 4 6 8.825z'/%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 0.75rem center;
    background-size: 0.75rem;
    padding-right: 2rem;
}

/* 进度条样式 */
.progress-bar__custom {
    transition: width 0.3s ease;
}
</style>